﻿<#
.SYNOPSIS
Compress a folder with recurse option

.DESCRIPTION
Compress a folder with recurse option

.PARAMETER source
Required. the xml element which contains the database connection defintion
#>
function Compress-Source
{
    [cmdletbinding(DefaultParameterSetName="none")]
	param
	(
		[parameter(Mandatory = $true,ValueFromPipeline=$false)] 
		[System.String]
		$Source,

        [Parameter(Mandatory=$true,ValueFromPipeline=$false)] 
		[System.String]
        $Destination,

        [Parameter(Mandatory=$false,ValueFromPipeline=$false)] 
		[Switch]
        $Force


	)
    Begin
    {
        $watch = [system.diagnostics.stopwatch]::StartNew() 
        write-verbose "Start Compress-Source from $Source to $Destination"
    }
    End
    {
        write-verbose "End Compress-Source from $Source to $Destination"
        $watch.Stop();
        Write-Verbose "Function duration : $($watch.Elapsed)"
    }
    Process
    {

        if ((Test-Path -Path $Destination -PathType Leaf))
        {
            if ($Force)
            {
                Remove-Item -Path $Destination -Force
            }
            else
            {
                #TODO FIle exists, what happen
            }
        }     

        #zip -r "D:\Backup\RCM\PatchIE10.zip" D:\Backup\RCM\PatchIE10\*.* 
        $rootFolder = [System.IO.Path]::GetDirectoryName($Source)
        Write-Verbose "Root folder is $rootFolder"

        if (-not (Test-Path -Path $rootFolder -PathType Container))
        {
            throw new System.Exception "Error to find the root folder"
        }
        Set-Location $rootFolder

        $CalculatedSource = $Source.replace("$rootFolder\", "")


        $commandToExecute = [String]::Format("zip.exe -r -T '{0}' '{1}'",$Destination,$CalculatedSource)
        $result = Invoke-ManagedCommand -CommandToExecute $commandToExecute

        Write-Output $result

    }
}


<#
.SYNOPSIS
Gets file encoding.
.DESCRIPTION
The Get-FileEncoding function determines encoding by looking at Byte Order Mark (BOM).
Based on port of C# code from http://www.west-wind.com/Weblog/posts/197245.aspx
.EXAMPLE
Get-ChildItem  *.ps1 | select FullName, @{n='Encoding';e={Get-FileEncoding $_.FullName}} | where {$_.Encoding -ne 'ASCII'}
This command gets ps1 files in current directory where encoding is not ASCII
.EXAMPLE
Get-ChildItem  *.ps1 | select FullName, @{n='Encoding';e={Get-FileEncoding $_.FullName}} | where {$_.Encoding -ne 'ASCII'} | foreach {(get-content $_.FullName) | set-content $_.FullName -Encoding ASCII}
Same as previous example but fixes encoding using set-content
#>
function Get-FileEncoding
{
    [CmdletBinding()] Param (
     [Parameter(Mandatory = $True, ValueFromPipelineByPropertyName = $True)] [string]$Path
    )

    [byte[]]$byte = get-content -Encoding byte -ReadCount 4 -TotalCount 4 -Path $Path

    if ( $byte[0] -eq 0xef -and $byte[1] -eq 0xbb -and $byte[2] -eq 0xbf )
    { Write-Output 'UTF8' }
    elseif ($byte[0] -eq 0xfe -and $byte[1] -eq 0xff)
    { Write-Output 'Unicode' }
    elseif ($byte[0] -eq 0 -and $byte[1] -eq 0 -and $byte[2] -eq 0xfe -and $byte[3] -eq 0xff)
    { Write-Output 'UTF32' }
    elseif ($byte[0] -eq 0x2b -and $byte[1] -eq 0x2f -and $byte[2] -eq 0x76)
    { Write-Output 'UTF7'}
    else
    { Write-Output 'ASCII' }
}


function Ensure-Directory
{
    [CmdletBinding()]
    Param (
        [Parameter(Mandatory = $True, ValueFromPipelineByPropertyName = $True)]
        [string]$Path
    )
    Begin
    {
        $watch = [system.diagnostics.stopwatch]::StartNew()
        $eventId = Publish-ToMiddlewareLogs -Log (Get-LogMessage -Command $PSCmdlet.MyInvocation.MyCommand -Message "Start" -AdditionalData $PSBoundParameters)
    }
    End
    {
        $watch.Stop()
        $eventId = Publish-ToMiddlewareLogs -Log (Get-LogMessage -Command $PSCmdlet.MyInvocation.MyCommand -UniqueId $eventId -Message "End" -AdditionalData @{Duration=$watch.Elapsed})
    }
    Process
    {
        try
        {
            
            if (Test-Path -Path $Path)
            {
                $existingFolder = Get-Item -Path $Path
                if ($existingFolder -and $existingFolder.GetType().Name -ne 'DirectoryInfo')
                {
                    throw "Already exist path '$path' but it is a file"
                }
                Write-Verbose "Directory '$Path' already exist"
                return
            }

            $folder = New-Item -Path $Path -ItemType Directory
        }
        catch [Exception]
        {
            Publish-ToMiddlewareLogs -Log (Get-LogMessage -Command $PSCmdlet.MyInvocation.MyCommand -UniqueId $eventId -Category Error -Message "Error" -AdditionalData @{Exception=$_}) | Out-Null
            throw
        }

    }

}
